package oa.dao.impl;

import java.sql.SQLException;
import java.util.Collection;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;

import oa.dao.ReplyDao;
import oa.dao.base.impl.BaseDaoImpl;
import oa.domain.forum.Forum;
import oa.domain.forum.Reply;
import oa.domain.forum.Topic;
import oa.domain.page.PageBean;
@Repository("replyDao")
public class ReplyDaoImpl extends BaseDaoImpl<Reply> implements ReplyDao {

	@Resource(name="hibernateTemplate")	
	public HibernateTemplate hibernateTemplate;
	
	@Resource
	private SessionFactory sessionFactory;
	
	@Override
	public Collection<Reply> getReplyByTopic(Topic topic) {
		// TODO Auto-generated method stub
		return (Collection<Reply>) this.hibernateTemplate.find("from Reply r where r.topic = ? order by r.postTime asc",topic);
	}

	/**
	 * 分页查询
	 */
	@Override
	public PageBean getPageBean( int currentPage,  Topic topic) {
		// TODO Auto-generated method stub
	    int pageSize = 10;
		int firstResult = (currentPage - 1) * pageSize;
		String hql = "FROM Reply r WHERE r.topic = ? ORDER BY r.postTime ASC";
		Query query = sessionFactory.getCurrentSession().createQuery(hql);
		query.setParameter(0, topic);
		query.setFirstResult(firstResult);
		query.setMaxResults(pageSize);
		List recordList = query.list();
	    hql = "select count(*) from Reply r where r.topic = ?";
	    query = sessionFactory.getCurrentSession().createQuery(hql);
		query.setParameter(0, topic);
		Long recordCount = (Long) query.uniqueResult();
		return new PageBean(currentPage, pageSize, recordCount.intValue(), recordList);
	}

}
